﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace YouHaoApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ExpenseController : ControllerBase
    {
        YouHaoContext context;
        public ExpenseController(YouHaoContext ctx)
        {
            context = ctx;
        }
        // GET api/<ExpenseController>/5
        [HttpGet("{userid}")]
        public IEnumerable<ExpenseModel> Get(int userid)
        {
            var list = context.Expenses.Where(r => r.UserId == userid);
            List<ExpenseModel> r = new List<ExpenseModel>();
            foreach (var item in list)
            {
                ExpenseModel m = new ExpenseModel
                {
                    UserId = item.UserId,
                    Amount = item.Amount,
                    CreateTime = item.CreateTime,
                    ExpenseId = item.ExpenseId,
                    Kilometres = item.Kilometres,
                    Litre = item.Litre,
                    Price = item.Price,
                    VehicleName = item.VehicleName
                };
                r.Add(m);
            }
            return r;
        }

        // POST api/<ExpenseController>
        [HttpPost]
        public void Post([FromBody] ExpenseModel value)
        {
            Expense expense = new Expense
            {
                Kilometres = value.Kilometres,
                UserId = value.UserId,
                Amount = value.Amount,
                VehicleName = value.VehicleName,
                Litre = value.Litre,
                Price = value.Price,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
            };
            context.Expenses.Add(expense);
            context.SaveChanges();
        }

        // PUT api/<ExpenseController>/5
        [HttpPut]
        public void Put([FromBody] ExpenseModel value)
        {
            Expense expense = new Expense
            {
                ExpenseId=value.ExpenseId,
                Kilometres = value.Kilometres,
                UserId = value.UserId,
                Amount = value.Amount,
                VehicleName = value.VehicleName,
                Litre = value.Litre,
                Price = value.Price,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
            };
            context.Expenses.Attach(expense);
            context.SaveChanges();
        }

        // DELETE api/<ExpenseController>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            var e = context.Expenses.FirstOrDefault(r => r.ExpenseId == id);
            if (e == null)
                return;
            context.Expenses.Remove(e);
            context.SaveChanges();
        }
    }
}
